<?php
session_start();
$root=preg_replace("/^(.*(yunshop|shante)).*$/Uisx","\\1",getcwd());
include("{$root}/myzhuaqu.php");
require_once("{$root}/vendor/autoload.php");
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\WebDriverExpectedCondition;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverWait;
use Facebook\WebDriver\Interactions\WebDriverActions;
use Facebook\WebDriver\WebDriverJavascriptExecutor;
use Facebook\WebDriver\Cookie;
use Facebook\WebDriver\Remote\RemoteWebElement;

//restartChromeDriver();

//$cookiestr=getDouyinCookie();
global $driver;
if($_REQUEST['cookie']!=""){
    $cookiestr=$_REQUEST['cookie']=trim(preg_replace("/cookie:\s*/i","",$_REQUEST['cookie']));
    file_put_contents("d:/wwwroot/www/shop/yunshop/cookie/douyin.txt",$_REQUEST['cookie']);
}
$url = $_REQUEST['url'];
gotoDouyinNewGoods();

function gotoDouyinNewGoods(){
    global $driver,$argv;

    if ($driver !== null) {
        $driver->quit();
        $driver = null;
    }

    //加载数据

    $json=file_get_contents("https://shop.shante.me/yunshop/data.php?item_id={$argv[1]}&json=true&t=".time()); ////438
    $data=json_decode($json,1);
    $_SESSION['item_id']=$argv[1];



    //关闭多移窗口
//    $output = array();
//    $return_var = 0;
//    exec('tasklist | findstr "chrome.exe"', $output, $return_var);
//    if ($return_var === 0) {
//        foreach ($output as $line) {
//            echo $line . PHP_EOL;
//            if (preg_match('/^chrome.exe\s*(\d+)\s+.*/', $line, $matches)) {
//                $pid = $matches[1];
//                $command = "taskkill /F /PID $pid"; // /F 表示强制终止进程
//                exec($command, $output, $return_var);
//            }
//        }
//    } else {
//        echo "Error executing command: " . $return_var . PHP_EOL;
//    }

    $cookiestr=file_get_contents("d:/wwwroot/www/shop/yunshop/cookie/douyin.txt");
    $options = new ChromeOptions();
    //$options->addArguments(['--headless']);  //不出现浏览器
    $options->addArguments(['--disable-blink-features=AutomationControlled']);
    $options->addArguments(['--disable-extensions']);
    $options->addArguments(['--disable-gpu']);
    $options->addArguments(['--disable-infobars']);
    $options->addArguments(['--disable-notifications']);
    $options->addArguments(['--disable-popup-blocking']);
    $options->addArguments(['--disable-web-security']);
    $options->addArguments(['--ignore-certificate-errors']);
    $options->addArguments(['--no-sandbox']);
    $options->addArguments(array('--bookmarks=1'));
    $options->setExperimentalOption("useAutomationExtension", false);
    $options->setExperimentalOption("excludeSwitches", ['enable-automation']);
    $options->addArguments(['--user-data-dir=/d/temp']);

    //exec("taskkill /IM chrome.exe /F");
    $capabilities = DesiredCapabilities::chrome();
    $capabilities->setCapability(ChromeOptions::CAPABILITY, $options);
    $driver = RemoteWebDriver::create('http://localhost:9515', $capabilities);
    $driver->get("https://fxg.jinritemai.com/ffa/mshop/homepage/index?item_id={$_SESSION['item_id']}");
    $driver->executeScript("window.resizeTo(screen.availWidth, screen.availHeight);");
    $driver->executeScript("window.moveTo(0, 0);");
    $wait = new WebDriverWait($driver, 10); // 设置最长等待时间为10秒
    $element = $wait->until(
        WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::xpath("//a[contains(text(), '商品创建')]"))
    );
    $driver->executeScript("window.resizeTo(screen.availWidth, screen.availHeight);");
    $actions = new WebDriverActions($driver);
    $actions->moveToElement($element)->perform();
    $element->click();
    $currentWindowHandle = $driver->getWindowHandle();
    $allWindowHandles = $driver->getWindowHandles();
    $newWindowHandle = null;
    foreach ($allWindowHandles as $handle) {
        if ($handle != $currentWindowHandle) {
            $newWindowHandle = $handle;
            break;
        }
    }
    $driver->switchTo()->window($newWindowHandle);
    try{
        $wait = new WebDriverWait($driver, 5);
        $element = $wait->until(
            WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::xpath("//span[contains(text(), '重新发布')]"))
        );
        $element->click();
    } catch (Exception $e) {

    }
    $wait = new WebDriverWait($driver, 10);
    try {
        $element = $wait->until(
            WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::xpath("//span[contains(text(), '返回旧版')]"))
        );
        $element->click();
    }catch (Exception $e){
        try{
            $wait = new WebDriverWait($driver, 5);
            $element = $wait->until(
                WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::xpath("//span[contains(text(), '重新发布')]"))
            );
            $element->click();
        } catch (Exception $e) {

        }
    }


    //选择类目
    $nn=explode(">",$data["category2"]);
    $wait = new WebDriverWait($driver, 10);
    try {
        $element = $wait->until(
            WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::xpath("//span[contains(text(),'{$nn[1]}')]"))
        );
    }catch(Exception $e){
        echo "加载普通商品页超时";
    }
    $actions = new WebDriverActions($driver);

    for($i=0;$i<count($nn);$i++){
        $index=($i<=1)?1:$i;
        try {
            if($i==0) {
                $el = $wait->until(
                    WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::xpath("//div[@class='ecom-g-tree-list-holder-inner']//span[contains(text(), '{$nn[$i]}')]"))
                );
            }elseif($i==1) {
                $el = $wait->until(
                    WebDriverExpectedCondition::visibilityOfElementLocated(WebDriverBy::xpath("//div[@class='ecom-g-tree-list-holder-inner']//span[contains(text(), '{$nn[$i]}')]"))
                );
            }else{
                $wait = new WebDriverWait($driver, 20);
                $el = $wait->until(
                    WebDriverExpectedCondition::visibilityOfElementLocated(WebDriverBy::xpath("//div[starts-with(@class,'index_cat".($index)."')]//span[contains(text(), '{$nn[$i]}')]"))
                );
                //$el=$eldiv->findElement(WebDriverBy::xpath(".//span[contains(text(), '{$nn[$i]}')]"));
            }
            $h=h($el);
            if ($h != "") {
                //$wait->until(WebDriverExpectedCondition::elementToBeClickable($el));
                $actions->moveToElement($el)->perform();
                $el->click();
            }
        }catch (\Facebook\WebDriver\Exception\WebDriverException $e){
            $el = $driver->findElement(WebDriverBy::xpath("//div[starts-with(@class,'index_cat{$i}')]//span[contains(text(), '{$nn[$i]}')]"));
            $el->click();
        }
    }

    //等待标题为商品创建的页面出现
    $wait = new WebDriverWait($driver, 20);
    // 使用WebDriverWait等待元素变得可点击
    $elementNext = $wait->until(
        WebDriverExpectedCondition::elementToBeClickable(WebDriverBy::xpath("//span[contains(text(),'下一步')]"))
    );
    //$actions->moveToElement($elementNext)->perform();
    $elementNext->click();
    $element = $wait->until(
        WebDriverExpectedCondition::titleContains('商品创建')
    );




//    $xpath = "//div[@attr-field-id and count(.//div[starts-with(@class, 'upload_buttonGroup')]) = 1]";
//    $elements = $driver->findElements(WebDriverBy::xpath($xpath));
//    for ($i=0;$i<count($elements);$i++) {
//        $element=$elements[$i];
//        $script = "return arguments[0].outerHTML;";
//        $outerHTML_div = (string) $driver->executeScript($script, [$element]);
//        //uploadFile($driver,$element);
//    }

    sleep(1);

//    赋值区
    uploadFileContent($driver,$data["images"]);
    input($driver,"商品标题",$data["name"]);
    $driver->findElement(WebDriverBy::xpath("//span[contains(text(),'一键智能推荐')]"))->click();

    select($driver,"品牌","无品牌");
    select($driver,"衣长","短款");
    select($driver,"风格","极简风");
    select($driver,"厚度","薄款");
    select($driver,"袖长","无袖");
    select($driver,"领型","圆领");
    select($driver,"服装版型","宽松型");
    allRequired($driver);
    for($i=0;$i<count($data["images"]);$i++){
        if($i==0){
            uploadFile($driver,"上传主图","",0,$data["images"][$i]);
        }else{
            uploadFile($driver,"上传辅助图","",0,$data["images"][$i]);
        }
    }

    if($data["video_url"]!="") {
        uploadFile($driver, "主图视频", "", 0, $data["video_url"]);
    }


//    $file="C:\Users\Administrator\Pictures\微信图片_20240128204308.jpg";
//    uploadFile($driver,"导购图","",0,$file);

//    $file="C:\Users\Administrator\Pictures\微信图片_20240128204308.jpg";
//    uploadFile($driver,"白底图","",0,$file);



//    //在一个包括<span>启用尺码表</span>的div中查找button并点击其
//    $divWithSpan = $driver->findElement(
//        WebDriverBy::xpath("//div/span[text()='启用尺码表']/parent::div")
//    );
//    $button = $divWithSpan->findElement(
//        WebDriverBy::xpath(".//button")
//    );
//    try{
//        $button->click();
//        //$driver->executeScript("arguments[0].aria-checked = true;", [$button]);
//    }catch (Exception $e){
//        sleep(1);
////        $button->click();
//    }
    sleep(10000);
    $driver->quit();

}

function uploadFile($driver,$upload_text,$other_text,$index=0,$file){
    $elements0 = $driver->findElements(WebDriverBy::cssSelector('div[class^="upload_text"]'));
    $htmls1=getOuterHTMLs($driver,$elements0,'div[class^="upload_text"]');
    createAttrId($driver,$elements0,"uploadBQ",'div[class^="upload_text"]');
    $elements=array();
    $elements1 = $driver->findElements(WebDriverBy::cssSelector('div[class^="upload_text"]'));
    $htmls2=getOuterHTMLs($driver,$elements1,'div[class^="upload_text"]');
    for ($i=0;$i<count($elements1);$i++) {
            if (strpos($htmls2[$i], $upload_text) !== false) {
                if ($other_text != "" && strpos($htmls2[$i], $other_text) == null) {
                    $elements[]=$elements1[$i];
                }elseif($other_text == ""){
                    $elements[]=$elements1[$i];
                }
            }
    }
    $htmls=getOuterHTMLs($driver,$elements,'div[class^="upload_text"]');
    $html=$htmls[$index];
    $element=$elements[$index];
    //$element = $driver->findElement(WebDriverBy::cssSelector("id^=[uploadBQ_]"));
    // 查找父级div元素
    $parentElement = $element->findElement(WebDriverBy::xpath('..'));
    if (strpos($parentElement->getAttribute('class'), 'upload_button') === 0) {
        $el = $element;
        $script = "return arguments[0].outerHTML;";
        $outerHTML_div = (string)$driver->executeScript($script, [$el]);
        $driver->executeScript("arguments[0].scrollIntoView({block: 'start'});", [$parentElement]);
        $actions = new WebDriverActions($driver);
        $actions->moveToElement($el)->perform();
        $actions->click();
        sleep(1);
        $el2 = $element->findElement(WebDriverBy::xpath("//div[contains(text(),'本地上传')]"));
        try {
            $actions->moveToElement($el2)->perform();
        }catch (ElementNotInteractableException $e){
            $el2 = $element->findElement(WebDriverBy::xpath("//div[contains(text(),'本地上传')]"));
        }catch (\Facebook\WebDriver\Exception\WebDriverException $e){

            $el2 = $element->findElement(WebDriverBy::xpath("//div[contains(text(),'本地上传')]"));
        }catch (Exception $e){
            $widthScript = "return Math.max(document.evaluate(\"//div[contains(text(),'本地上传')]\", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.offsetWidth, 0);";
            $width = $driver->executeScript($widthScript);

            $heightScript = "return Math.max(document.evaluate(\"//div[contains(text(),'本地上传')]\", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.offsetHeight, 0);";
            $height = $driver->executeScript($heightScript);
            $el2 = $element->findElement(WebDriverBy::xpath("//div[contains(text(),'本地上传')]"));
        }
        try {
            $actions->moveToElement($el2)->perform();
            shell_exec("D:\AutoIt3\AutoIt3.exe D:\wwwroot\www\shop\yunshop\au3\closewin.au3");
            $el2->click();
        }catch (Exception $e){
            $actions->moveToElement($el2)->perform();
            shell_exec("D:\AutoIt3\AutoIt3.exe D:\wwwroot\www\shop\yunshop\au3\closewin.au3");
            $el2->click();
        }
//            $autoitContent = 'WinWait("打开", "", 10) ;
//ControlFocus("打开","","Edit1");
//ControlSetText("打开","","Edit1",$CmdLine[1]) //执行命令参数行
//ControlClick("打开", "", "Button1");';
//            $autoItScript = "upload_file.au3";
            //file_put_contents("upload_file.au3", $autoitContent);
            shell_exec("D:\AutoIt3\AutoIt3.exe D:\wwwroot\www\shop\yunshop\au3\upload_file.au3 {$file}");
//            $wait = new Facebook\WebDriver\WebDriverWait($driver, 5);
//            try {
//                $el3=$driver->wait()->until(
//                    WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::xpath("//span[contains(text(),'应用')]"))
//                );
//                try {
//                    $elements = $driver->findElements(WebDriverBy::xpath("//span[contains(text(),'应用')]"));
//                    createAttrId($driver, $elements, "yingyong");
//                    $element=$driver->wait()->until(
//                        WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::id("yingyong_1"))
//                    );
//                    //getOuterHTML($driver, $elements[0]);
//                    $actions = new WebDriverActions($driver);
//                    $actions->moveToElement($elements[1])->perform();
//                    $element[0]->click();
//                }catch (Exception $e){
//                    echo 2;
//                }
//            } catch (Facebook\WebDriver\Exception\TimeoutException $e) {
//                echo "Element with ID '应用' did not appear within 10 seconds.";
//            }
            //$driver->findElement(WebDriverBy::xpath("//span[contains(text(),'上传')]"))->click();
        }
    sleep(2);
}

function uploadFileContent($driver,$images){
    $wait = new WebDriverWait($driver, 10);
    try {

        for($i=0;$i<count($images);$i++) {

            do {
                try {
                    $element=$driver->wait()->until(
                        WebDriverExpectedCondition::visibilityOfElementLocated(WebDriverBy::xpath("//div[@attr-field-id='商品详情']//span[contains(text(),'上传图片')]"))
                    );

                    //移动页面到商品详情位置
                    $el3=$driver->findElement(WebDriverBy::xpath("//span[contains(text(),'商品详情')]"));
                    $driver->executeScript("arguments[0].scrollIntoView({block: 'start'});", [$el3]);
                    shell_exec("D:\AutoIt3\AutoIt3.exe D:\wwwroot\www\shop\yunshop\au3\closewin.au3");
                    $actions = new WebDriverActions($driver);
                    $actions->moveToElement($element)->perform();

                    $element->click();

                    $el = $driver->findElement(WebDriverBy::xpath("//div[contains(text(), '本地上传')]"));
                    $actions = new WebDriverActions($driver);
                    $actions->moveToElement($el)->perform();
                    $el->click();
//                    $autoIt = new COM("AutoItX3.Control") or die("无法创建AutoIt对象");
//                    $autoIt->Run("upload_file.au3", $images[$i]);
                    shell_exec("D:\AutoIt3\AutoIt3.exe D:\wwwroot\www\shop\yunshop\au3\upload_file.au3 {$images[$i]}");
                    break;
                } catch (Exception $e) {
                    sleep(1);
                    continue;
                }
            }while(true);
        }
    }catch (Exception $e){
       echo $e;
    }
}
function input($driver,$title,$value){
    //在一个包括属性attr-field-id="商品标题"的div中，找到input
    $inputElement = $driver->findElement(
        WebDriverBy::cssSelector('div[attr-field-id="'.$title.'"] input')
    );
    $inputElement->sendKeys($value);
}

function select($driver,$title,$value)
{
    $divElement = $driver->findElement(
        WebDriverBy::cssSelector('div[attr-field-id="' . $title . '"]')
    );
    //$driver->findElements(WebDriverBy::cssSelector('div[attr-field-id="' . $title . '"] input'));
    $el = $divElement->findElement(WebDriverBy::cssSelector("input"));
    $script = "return arguments[0].outerHTML;";
    $outerHTML_div = (string)$driver->executeScript($script, [$divElement]);
    $outerHTML_input = (string)$driver->executeScript($script, [$el]);
    if ($el->getAttribute("type") == "search") {
        $driver->executeScript("arguments[0].scrollIntoView({behavior: 'smooth', block: 'start'});", [$el]);
        try {
            //点击使下拉菜单弹出
            $el->click();
            //得到菜单内容
            preg_match("/attr-field-id=\"([^<>]*)\"/Uisx", $outerHTML_div, $nn);
            $popdiv = $driver->findElement(WebDriverBy::cssSelector(".auto-dropdown-id-{$nn[1]}"));
            $el2 = $popdiv->findElement(WebDriverBy::cssSelector("div.rc-virtual-list-holder-inner>div"));
            // 定位到第一个 ecom-g-select-item 元素
            $activeOptions = $popdiv->findElements(WebDriverBy::cssSelector(".ecom-g-select-item-option-content"));
            for($i=0;$i<count($activeOptions);$i++){
                $activeOption=$popdiv->findElements(WebDriverBy::cssSelector(".ecom-g-select-item-option-content"))[$i];
                $option=getOuterHTML($driver,$activeOption);
                if(preg_match("/>{$value}</Uisx",$option)){
                    $actions = new WebDriverActions($driver);
                    $actions->moveToElement($activeOption)->perform();
                    // $driver->manage()->timeouts()->implicitlyWait(2000); // 隐式等待（可选）
                    $activeOption->click();
                    break;
                }
            }

        } catch (Exception $e) {

        }
    }
}

function getDouyinCookie(){
    $options = new ChromeOptions();
    //$options->addArguments(['--headless']);  //不出现浏览器
    $options->addArguments(['--disable-blink-features=AutomationControlled']);
    $options->addArguments(['--disable-extensions']);
    $options->addArguments(['--disable-gpu']);
    $options->addArguments(['--disable-infobars']);
    $options->addArguments(['--disable-notifications']);
    $options->addArguments(['--disable-popup-blocking']);
    $options->addArguments(['--disable-web-security']);
    $options->addArguments(['--ignore-certificate-errors']);
    $options->addArguments(['--no-sandbox']);
    $options->setExperimentalOption("useAutomationExtension", false);
    $options->setExperimentalOption("excludeSwitches", ['enable-automation']);
//$options->addArguments(['--start-maximized']);
//chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])
    $options->addArguments(['--user-data-dir=/d/temp']);

    $capabilities = DesiredCapabilities::chrome();
    $capabilities->setCapability(ChromeOptions::CAPABILITY, $options);
    $driver = RemoteWebDriver::create('http://localhost:9515', $capabilities);
//$driver->setExperimentalOption('excludeSwitches', ['enable-automation', 'useAutomationExtension']);
//$driver->execute_cdp_cmd('Network.setUserAgentOverride', '{"userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"}');

    $driver->get('https://fxg.jinritemai.com/login/common');
    $script = 'Object.defineProperty(navigator, "webdriver", {get: () => undefined,});';
    $driver->executeScript($script);
    $driver->findElement(WebDriverBy::cssSelector('.email'))->click();
    $element = $driver->findElement(WebDriverBy::cssSelector('input[name=email]'));
    $element->sendKeys("yzs1013@163.com");
    $element = $driver->findElement(WebDriverBy::cssSelector('input[name=password]'));
    $element->sendKeys("~159456!aA");
    $element = $driver->findElement(WebDriverBy::cssSelector('input.auxo-checkbox-input'));
    if(!$element->isSelected) $element->click();
    $driver->findElement(WebDriverBy::className('account-center-action-button'))->click();
//    $wait->until(
//        function ($driver) {
//            return $driver->findElement(WebDriverBy::cssSelector('nav-title'));
//        }
//    );
    $wait = new WebDriverWait($driver, 10);
    $wait->until(
        function ($driver) {
            $currentUrl = $driver->getCurrentUrl();
            return strpos($currentUrl, 'homepage') !== false;
        }
    );
    $driver->findElementByXPath("//a[contains(text(), '商品创建')]")->click();
    $cookies = $driver->manage()->getCookies();
    $cookiestr="";
    for($i=0;$i<count($cookies);$i++){
        $cookiestr.=$cookies[$i]->getName()."=".$cookies[$i]->getValue().";";
    }
    $driver->quit();
    file_put_contents("d:/wwwroot/www/shop/yunshop/cookie/douyin.txt",$_REQUEST['cookie']);
    return $cookiestr;
}

function allRequired($driver){
    $xpath = "//span[starts-with(@class, 'index_required')]/ancestor::div[count(descendant::input) = 1]";
    $divs = $driver->findElements(WebDriverBy::xpath($xpath));
    // 遍历这些 div
    $inarr=array();
    foreach ($divs as $div) {
        $script = "return arguments[0].outerHTML;";
        $outerHTML_div = (string) $driver->executeScript($script, [$div]);
        preg_match("/attr-field-id=\"([^<>]*)\"/Uisx",$outerHTML_div,$nn);
        if(!in_array($nn[1],$inarr)){
            $el=$div->findElement(WebDriverBy::cssSelector("input"));
            $outerHTML_input = (string) $driver->executeScript($script, [$el]);
            if($el->getAttribute("type")=="search") {
                //if($nn[1]!="运费模板") continue;
                $driver->executeScript("arguments[0].scrollIntoView({behavior: 'smooth', block: 'start'});", [$el]);
                try {
                    //点击使下拉菜单弹出
                    $el->click();
                    //得到菜单内容
                    $popdiv=$driver->findElement(WebDriverBy::cssSelector(".auto-dropdown-id-{$nn[1]}"));
                    $el2=$popdiv->findElement(WebDriverBy::cssSelector("div.rc-virtual-list-holder-inner>div"));
                    // 定位到第一个 ecom-g-select-item 元素
                    $firstOption = $popdiv->findElement(WebDriverBy::cssSelector('.ecom-g-select-item-option:nth-child(1)'));
                    $actions = new WebDriverActions($driver);
                    $actions->moveToElement($firstOption)->perform();
                    // $driver->manage()->timeouts()->implicitlyWait(2000); // 隐式等待（可选）
                    $firstOption->click();

                }catch(Exception $e){

                }
                //$el->clear()->sendKeys("运动风");
                //$driver->executeScript("arguments[0].blur();", [$el]);
            }
            $inarr[]=$nn[1];
        }
    }
}

function getOuterHTMLs($webdriver, $elements,$cssSelector) {
    $outerHTMLs = [];
    foreach ($elements as $element) {
        try {
            $outerHTML = $webdriver->executeScript("return arguments[0].outerHTML;", [$element]);
            $outerHTMLs[] = $outerHTML;
        }catch (StaleElementReferenceException $e){
            $elements = $webdriver->findElements(WebDriverBy::cssSelector('div[class^="upload_text"]'));
            return getOuterHTMLs($webdriver, $elements,$cssSelector);
        }catch (WebDriverExceptionn $e){
            $elements = $webdriver->findElements(WebDriverBy::cssSelector('div[class^="upload_text"]'));
            return getOuterHTMLs($webdriver, $elements,$cssSelector);
        }catch (Exception $e){
            $elements = $webdriver->findElements(WebDriverBy::cssSelector('div[class^="upload_text"]'));
            return getOuterHTMLs($webdriver, $elements,$cssSelector);
        }
    }
    return $outerHTMLs;
}

function getOuterHTML($webdriver, $element) {
    $outerHTML = $webdriver->executeScript("return arguments[0].outerHTML;", [$element]);
    return $outerHTML;
}

function h($elements) {
    global $driver;
    if(array_key_exists(0,$elements)){
        $outerHTMLs = [];
        foreach ($elements as $element) {
            $outerHTML = $driver->executeScript("return arguments[0].outerHTML;", [$element]);
            $outerHTMLs[] = $outerHTML;
        }
        return $outerHTMLs;
    }else {
        $outerHTML = $driver->executeScript("return arguments[0].outerHTML;", [$elements]);
        return $outerHTML;
    }
    return "";
}

function createAttrId($driver,$elements,$pre="uploadBQ"){
    for ($i=0;$i<count($elements);$i++) {
        $element=$elements[$i];
        try {
            $id = $element->getAttribute('id');
            if (strpos($id, $pre.'_') === false) {
                $driver->executeScript("arguments[0].setAttribute('id', '{$pre}_{$i}');", [$element]);
            }
        }catch (StaleElementReferenceException $e){
            $elements0 = $driver->findElements(WebDriverBy::cssSelector('div[class^="upload_text"]'));
            createAttrId($driver,$elements,"uploadBQ",$pre);
            break;
        }

    }
}
